<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small" v-if="mode !== 'select'">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="企业" prop="workCorpId">
                            <el-select v-model="condition.search.workCorpId" placeholder="请选择企业"
                                       style="width:200px;">
                                <el-option
                                    v-for="item in corps"
                                    :key="item.id"
                                    :label="item.corpName"
                                    :value="item.id">
                                    {{ item.corpName }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="部门名称" prop="name">
                            <el-input v-model="condition.search.name"
                                      placeholder="部门名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" @click="sync">同步</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="danger" @click="changeMode">切换显示</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            v-if="mode === 'list' || mode === 'select'"
            size="small"
            ref="departmentTable"
            id="departmentTable"
            :data="tableData"
            @selection-change="handleSelectionChange"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column type="selection" width="55" v-if="mode === 'select'"></el-table-column>
            <el-table-column label="序号" width="60">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="departmentId"
                label="部门ID">
            </el-table-column>
            <el-table-column
                prop="parentDepartmentId"
                label="父部门ID">
            </el-table-column>
            <el-table-column
                prop="order"
                label="排序">
            </el-table-column>
            <el-table-column
                prop="name"
                label="部门名称">
            </el-table-column>
            <el-table-column
                prop="leader"
                label="部门领导">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
            <el-table-column
                v-if="mode === 'list'"
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                v-if="mode === 'list'"
                prop="syncTime"
                label="同步时间">
            </el-table-column>
            <el-table-column
                v-if="mode === 'list'"
                label="操作"
                fixed="right"
                width="60">
                <template v-slot="scope">
                    <div>
                        <el-button @click="onRefresh(scope.row)" type="text" size="small">刷新</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-tree
            v-if="mode === 'tree'"
            :data="treeData"
            show-checkbox
            default-expand-all
            :expand-on-click-node="false"
            node-key="id"
            ref="tree"
            :props="defaultProps"
            highlight-current>
            <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                    <el-button type="text" size="small" @click="onRefresh(data)">刷新</el-button>
                </span>
            </span>
        </el-tree>
        <el-pagination
            background
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[30, 60, 90, 120]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px">
                <el-form-item label="公司ID">
                    <el-input v-model="addOrUpdateForm.corpId"
                              placeholder="公司ID"></el-input>
                </el-form-item>
                <el-form-item label="部门ID">
                    <el-input v-model="addOrUpdateForm.departmentId"
                              placeholder="部门ID"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="父部门ID">
                    <el-input v-model="addOrUpdateForm.parentDepartmentId"
                              placeholder="父部门ID"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="addOrUpdateForm.order"
                              placeholder="排序"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
                <el-form-item label="部门名称">
                    <el-input v-model="addOrUpdateForm.name"
                              placeholder="部门名称"></el-input>
                </el-form-item>
                <el-form-item label="部门英文名称">
                    <el-input v-model="addOrUpdateForm.nameEn"
                              placeholder="部门英文名称"></el-input>
                </el-form-item>
                <el-form-item label="部门领导">
                    <el-input v-model="addOrUpdateForm.leader"
                              placeholder="部门领导"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addOrUpdateDialogVisible = false">取 消</el-button>
                <el-button @click="addOrUpdateConfirm" type="primary">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addWorkDepartment,
    deleteWorkDepartment,
    getWorkCorpByPage,
    getWorkDepartmentByPage,
    refreshWorkDepartment,
    syncWorkDepartment,
    updateWorkDepartment
} from '@/api/api'

export default {
    name: "WorkDepartment",
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 30,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},
            // 公司信息
            corps: [],

            // 树形数据
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'name'
            },

            departmentSelected: [],

            beforeMode: '',
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        size: {
            type: String,
            default: 'small'
        },
        mode: {
            type: String,
            default: 'list'
        },
        // 选中的行
        selected: {
            type: Array,
            default: () => []
        },
        workCorpId: String
    },
    watch: {
        selected: function (val, oldVal) {
            this.selected = val;
            this.setChecked();
        },
        workCorpId: function (val, oldVal) {
            this.condition.search.workCorpId = val;
        }
    },
    methods: {
        changeMode() {
            if (this.mode == 'tree') {
                this.mode = this.beforeMode;
            } else {
                this.beforeMode = this.mode;
                this.mode = 'tree';
            }
        },
        handleSelectionChange(val) {
            this.departmentSelected = val;
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },

        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#departmentTable', '数据.xlsx');
        },
        add: function () {
            addWorkDepartment(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        update: function () {
            updateWorkDepartment(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        sync: function () {
            if (!this.condition.search.workCorpId) {
                this.$message({
                    type: 'error',
                    message: '请先选择企业!'
                });
                return;
            }
            this.$confirm('请确认是否同步, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                syncWorkDepartment({workCorpId: this.condition.search.workCorpId}).then(data => {
                    if (data.respCode == 1000) {
                        this.$message({
                            type: 'success',
                            message: '同步成功!'
                        });
                        this.getData();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onRefresh: function (row) {
            this.$confirm('请确认是否刷新, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                refreshWorkDepartment({id: row.id}).then(data => {
                    if (data.respCode == 1000) {
                        this.$message({
                            type: 'success',
                            message: '刷新成功!'
                        });
                        this.getData();
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteWorkDepartment({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取公司列表
        getCorps: function () {
            let condition = {
                page: 1,
                rows: 100,
                search: {}
            };
            getWorkCorpByPage(condition).then(data => {
                this.corps = data.body.rows;
            });
        },
        // list转换为tree，支持多级
        toTree: function (arr, parentId) {
            let temp = [];
            let treeArr = arr;
            treeArr.forEach((item, index) => {
                if (item.parentDepartmentId === parentId) {
                    // 递归调用
                    let result = this.toTree(treeArr, treeArr[index].departmentId);
                    if (result.length > 0) {
                        treeArr[index].children = result;
                    }
                    temp.push(treeArr[index]);
                }
            })
            return temp;
        },
        // 获取表格数据
        getData: function () {
            if (this.workCorpId) {
                this.condition.search.workCorpId = this.workCorpId;
            }
            getWorkDepartmentByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
                if (this.mode === 'select') {
                    this.setChecked();
                }
                this.tableData.sort((a, b) => {
                    return b.order - a.order
                })
                console.log(this.tableData);
                this.treeData = this.toTree(this.tableData, 0);
                console.log(this.treeData);
            });
            this.getCorps();
        },
        // 设置多选
        setChecked: function () {
            this.$refs.departmentTable.clearSelection();
            this.selected.forEach(item => {
                this.$nextTick(() => {
                    this.tableData.find(obj => {
                        if (item.id === obj.id) {
                            this.$refs.departmentTable.toggleRowSelection(obj, true)
                        }
                    })
                })
            })
        }
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>
